package com.demo.demoproject.utils;

import com.demo.demoproject.constants.MailConstants;
import com.demo.demoproject.domain.Result;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.MailSender;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMailMessage;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.text.MessageFormat;

import static com.demo.demoproject.constants.MailConstants.*;

@Slf4j
@Component
@RequiredArgsConstructor
public class CaptchaGenerator {
    @Autowired
    private static MailSender mailsender;
    @Autowired
    private static TemplateEngine templateEngine;

    /**
     * 生成验证码
     * @param length 验证码长度
     * @return 验证码
     * @throws IllegalArgumentException 如果 length 小于等于 0
     */
    @NotNull
    public static String getRandomCaptcha(@NotNull Integer length) {
        // 验证码长度不能小于等于0
        if (length <= 0) {
            throw new IllegalArgumentException("Length should be greater than 0.");
        }

        // 初始化 StringBuilder
        StringBuilder captcha = new StringBuilder(length);

        // 生成验证码
        for (int i = 0; i < length; i++) {
            int randomIndex = RANDOM.nextInt(CHAR_SET.length());
            char randomChar = CHAR_SET.charAt(randomIndex);
            captcha.append(randomChar);
        }

        return captcha.toString();
    }
}
